package Thread.day01;

/**
 * 使用同步代码块解决继承Thread类的线程安全问题
 */
public class Demo4 {
    public static void main(String[] args) {
        window3 w1 = new window3();
        window3 w2 = new window3();
        window3 w3 = new window3();
        w1.setName("窗口1");
        w2.setName("窗口2");
        w3.setName("窗口3");
        w1.start();
        w2.start();
        w3.start();
    }


}
class window3 extends Thread{
    private  static int ticket = 100;//必须定义静态变量，方式三个类实例化三次
//    private static Object object = new Object();必须是静态对象，因为当前类要实例化三个对象
    @Override
    public void run() {
        while(true){
//            synchronized (object){或者
              synchronized (window3.class){
                  //通过当前类的类对象window3只会加载一次
                if(ticket>0){
                    try {
                        Thread.sleep(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(getName()+"卖出了票号为"+ticket);
                    ticket--;
                }else {
                    break;
                }
            }

        }
    }
}
